home *** CD-ROM | disk | FTP | other *** search
/ The Atari Compendium / The Atari Compendium (Toad Computers) (1994).iso / files / prgtools / gnustuff / tos / othergnu / texinf~1.zoo / texinfo.st / util / texindex.c < prev   
Encoding:
C/C++ Source or Header  |  1993-06-23  |  42.4 KB  |  1,798 lines

  1. /* Prepare TeX index dribble output into an actual index.
  2.  
  3.    Version 1.45
  4.  
  5.    Copyright (C) 1987, 1991, 1992 Free Software Foundation, Inc.
  6.  
  7.    This program is free software; you can redistribute it and/or modify
  8.    it under the terms of the GNU General Public License as published by
  9.    the Free Software Foundation; either version 2, or (at your option)
  10.    any later version.
  11.  
  12.    This program is distributed in the hope that it will be useful,
  13.    but WITHOUT ANY WARRANTY; without even the implied warranty of
  14.    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  15.    GNU General Public License for more details.
  16.  
  17.    You should have received a copy of the GNU General Public License
  18.    along with this program; if not, write to the Free Software
  19.    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */
  20.  
  21.  
  22. #include <stdio.h>
  23. #include <ctype.h>
  24. #include <errno.h>
  25. #include "getopt.h"
  26.  
  27. #if defined (STDC_HEADERS)
  28. #  include <string.h>
  29. #  include <stdlib.h>
  30. #  if (!defined (bzero) && !defined(atarist))
  31. #    define bzero(p, n) memset((p), '\0', (n))
  32. #  endif /* !bzero */
  33. #else /* !STDC_HEADERS */
  34. extern int errno;
  35. char *getenv (), *malloc (), *realloc ();
  36. void bzero ();
  37. #endif /* !STDC_HEADERS */
  38.  
  39. #ifndef __PROTO
  40. #if defined(STDC_HEADERS)
  41. # define __PROTO(s) s
  42. #else
  43. # define __PROTO(s) ()
  44. #endif
  45. #endif
  46.  
  47. #if defined (HAVE_UNISTD_H)
  48. #  include <unistd.h>
  49. #else /* !HAVE_UNISTD_H */
  50. extern long lseek __PROTO((int, long, int));
  51. #endif /* !HAVE_UNISTD_H */
  52.  
  53. extern char *mktemp __PROTO((char *));
  54.  
  55. #if defined (VMS)
  56. #  if !defined (VAX11C)
  57. #    define noshare
  58. #  endif /* !VAX11C */
  59. #  include <perror.h>
  60. extern noshare int sys_nerr;
  61. extern noshare char *sys_errlist[];
  62.  
  63. #  include <file.h>
  64.  
  65. #  define TI_NO_ERROR ((1 << 28) | 1)
  66. #  define TI_FATAL_ERROR ((1 << 28) | 4)
  67. #  define unlink delete
  68.  
  69. #else /* !VMS */
  70.  
  71. extern int sys_nerr;
  72. extern char *sys_errlist[];
  73.  
  74. #  if defined (HAVE_SYS_FCNTL_H)
  75. #    include <sys/types.h>
  76. #    include <sys/fcntl.h>
  77. #  endif /* HAVE_SYS_FCNTL_H */
  78.  
  79. #  if defined (_AIX) || !defined (_POSIX_VERSION)
  80. #    include <sys/file.h>
  81. #  else /* !AIX && _POSIX_VERSION */
  82. #    if !defined (HAVE_SYS_FCNTL_H)
  83. #      include <fcntl.h>
  84. #    endif /* !HAVE_FCNTL_H */
  85. #  endif /* !_AIX && _POSIX_VERSION */
  86. #  define TI_NO_ERROR 0
  87. #  define TI_FATAL_ERROR 1
  88. #endif /* !VMS */
  89.  
  90. #if !defined (SEEK_SET)
  91. #  define SEEK_SET 0
  92. #  define SEEK_CUR 1
  93. #  define SEEK_END 2
  94. #endif /* !SEEK_SET */
  95.  
  96. /* When sorting in core, this structure describes one line
  97.    and the position and length of its first keyfield.  */
  98. struct lineinfo
  99. {
  100.   char *text;        /* The actual text of the line. */
  101.   union {
  102.     char *text;        /* The start of the key (for textual comparison). */
  103.     long number;    /* The numeric value (for numeric comparison). */
  104.   } key;
  105.   long keylen;        /* Length of KEY field. */
  106. };
  107.  
  108. /* This structure describes a field to use as a sort key. */
  109. struct keyfield
  110. {
  111.   int startwords;    /* Number of words to skip. */
  112.   int startchars;    /* Number of additional chars to skip. */
  113.   int endwords;        /* Number of words to ignore at end. */
  114.   int endchars;        /* Ditto for characters of last word. */
  115.   char ignore_blanks;    /* Non-zero means ignore spaces and tabs. */
  116.   char fold_case;    /* Non-zero means case doesn't matter. */
  117.   char reverse;        /* Non-zero means compare in reverse order. */
  118.   char numeric;        /* Non-zeros means field is ASCII numeric. */
  119.   char positional;    /* Sort according to file position. */
  120.   char braced;        /* Count balanced-braced groupings as fields. */
  121. };
  122.  
  123. /* Vector of keyfields to use. */
  124. struct keyfield keyfields[3];
  125.  
  126. /* Number of keyfields stored in that vector.  */
  127. int num_keyfields = 3;
  128.  
  129. /* Vector of input file names, terminated with a null pointer. */
  130. char **infiles;
  131.  
  132. /* Vector of corresponding output file names, or NULL, meaning default it
  133.    (add an `s' to the end). */
  134. char **outfiles;
  135.  
  136. /* Length of `infiles'. */
  137. int num_infiles;
  138.  
  139. /* Pointer to the array of pointers to lines being sorted. */
  140. char **linearray;
  141.  
  142. /* The allocated length of `linearray'. */
  143. long nlines;
  144.  
  145. /* Directory to use for temporary files.  On Unix, it ends with a slash.  */
  146. char *tempdir;
  147.  
  148. /* Start of filename to use for temporary files.  */
  149. char *tempbase;
  150.  
  151. /* Number of last temporary file.  */
  152. int tempcount;
  153.  
  154. /* Number of last temporary file already deleted.
  155.    Temporary files are deleted by `flush_tempfiles' in order of creation.  */
  156. int last_deleted_tempcount;
  157.  
  158. /* During in-core sort, this points to the base of the data block
  159.    which contains all the lines of data.  */
  160. char *text_base;
  161.  
  162. /* Additional command switches .*/
  163.  
  164. /* Nonzero means do not delete tempfiles -- for debugging. */
  165. int keep_tempfiles;
  166.  
  167. /* The name this program was run with. */
  168. char *program_name;
  169.  
  170. struct linebuffer
  171. {
  172.   long size;
  173.   char *buffer;
  174. };
  175.  
  176. /* Forward declarations of functions in this file. */
  177.  
  178. int  main __PROTO((int argc, char **argv));
  179. void usage __PROTO((void));
  180. void decode_command __PROTO((int argc, char **argv));
  181. char *maketempname __PROTO((int count));
  182. void flush_tempfiles __PROTO((int to_count));
  183. char *tempcopy __PROTO((int idesc));
  184. int compare_full __PROTO((char **line1, char **line2));
  185. int compare_prepared __PROTO((struct lineinfo *line1, struct lineinfo *line2));
  186. int compare_general __PROTO((char *str1, char *str2,
  187.                  long pos1, long pos2, int use_keyfields));
  188. char *find_field __PROTO((struct keyfield *keyfield, char *str,
  189.               long *lengthptr));
  190. char *find_pos __PROTO((char *str, int words, int chars, int ignore_blanks));
  191. char *find_braced_pos __PROTO((char *str, int words,
  192.                    int chars, int ignore_blanks));
  193. char *find_braced_end __PROTO((char *str));
  194. long find_value __PROTO((char *start, long length));
  195. void init_char_order __PROTO((void));
  196. int compare_field __PROTO((struct keyfield *keyfield,
  197.                char *start1, long length1, long pos1,
  198.                char *start2, long length2, long pos2));
  199. void initbuffer __PROTO((struct linebuffer *linebuffer));
  200. long readline __PROTO((struct linebuffer *linebuffer, FILE *stream));
  201. void sort_offline __PROTO((char *infile, /* int nfiles, */
  202.                long total, char *outfile));
  203. void sort_in_core __PROTO((char *infile, long total, char *outfile));
  204. char **parsefile __PROTO((char *filename, char **nextline,
  205.               char *data, long size));
  206. void init_index __PROTO((void));
  207. void indexify __PROTO((char *line, FILE *ostream));
  208. void finish_index __PROTO((FILE *ostream));
  209. void writelines __PROTO((char **linearray, int nlines, FILE *ostream));
  210. int merge_files __PROTO((char **infiles, int nfiles, char *outfile));
  211. int merge_direct __PROTO((char **infiles, int nfiles, char *outfile));
  212. void fatal __PROTO((char *s1, char *s2));
  213. void error __PROTO((char *s1, char *s2));
  214. void perror_with_name __PROTO((char *name));
  215. void pfatal_with_name __PROTO((char *name));
  216. char *concat __PROTO((char *s1, char *s2, char *s3));
  217. void *xmalloc __PROTO((size_t nbytes));
  218. void *xrealloc __PROTO((void *pointer, size_t nbytes));
  219. int memory_error __PROTO((char *callers_name, size_t bytes_wanted));
  220.  
  221. #ifdef NeXT
  222. extern int open(const char *, int, ...), close(int);
  223. extern int read(int, void *, int), write(int, const void *, int);
  224. extern int unlink (const char *);
  225. #endif /* NeXT */
  226.  
  227. #ifdef atarist
  228. /* #include <unistd.h> */ /* clash with getopt.h */
  229. extern int open (const char *, int, ...), close(int);
  230. extern long _read (int, void *, unsigned long);
  231. extern long _write (int, const void *, unsigned long);
  232. extern int unlink (const char *);
  233. #define read _read
  234. #define write _write
  235. #endif /* atarist */
  236.  
  237.  
  238. #define MAX_IN_CORE_SORT 500000L
  239.  
  240. int
  241. main (argc, argv)
  242.      int argc;
  243.      char **argv;
  244. {
  245.   int i;
  246.  
  247.   tempcount = 0;
  248.   last_deleted_tempcount = 0;
  249.   program_name = argv[0];
  250.  
  251.   /* Describe the kind of sorting to do. */
  252.   /* The first keyfield uses the first braced field and folds case. */
  253.   keyfields[0].braced = 1;
  254.   keyfields[0].fold_case = 1;
  255.   keyfields[0].endwords = -1;
  256.   keyfields[0].endchars = -1;
  257.  
  258.   /* The second keyfield uses the second braced field, numerically. */
  259.   keyfields[1].braced = 1;
  260.   keyfields[1].numeric = 1;
  261.   keyfields[1].startwords = 1;
  262.   keyfields[1].endwords = -1;
  263.   keyfields[1].endchars = -1;
  264.  
  265.   /* The third keyfield (which is ignored while discarding duplicates)
  266.      compares the whole line. */
  267.   keyfields[2].endwords = -1;
  268.   keyfields[2].endchars = -1;
  269.  
  270.   decode_command (argc, argv);
  271.  
  272. #ifndef atarist
  273.   tempbase = mktemp (concat ("txiXXXXXX", "", ""));
  274. #else  /* atarist */
  275.   /* we are somewhat more crowded with file names here */
  276.   tempbase = mktemp (concat ("txiXXXXX", "", ""));
  277. #endif /* atarist */
  278.  
  279.   /* Process input files completely, one by one.  */
  280.  
  281.   for (i = 0; i < num_infiles; i++)
  282.     {
  283.       int desc;
  284.       long ptr;
  285.       char *outfile;
  286.  
  287.       desc = open (infiles[i], O_RDONLY, 0);
  288.       if (desc < 0)
  289.     pfatal_with_name (infiles[i]);
  290.       lseek (desc, 0L, SEEK_END);
  291.       ptr = lseek (desc, 0L, SEEK_CUR);
  292.  
  293.       close (desc);
  294.  
  295.       outfile = outfiles[i];
  296.       if (!outfile)
  297.     {
  298. #ifndef atarist
  299.       outfile = concat (infiles[i], "s", "");
  300. #else  /* atarist */
  301.       /* MessyDOS strikes again */
  302.       char *ptr, *dot;
  303.       int  idx;
  304.       void dos2unx __PROTO((const char*, char *));
  305.  
  306.       dos2unx(infiles[i], infiles[i]);  /* makes life more enjoyable */
  307.       if (0 == (ptr = strrchr(infiles[i], '/')))
  308.         ptr = infiles[i];
  309.       else
  310.         ptr += 1;
  311.       if (0 == (dot = strchr(ptr, '.')))
  312.         outfile = concat (infiles[i], ".s", "");
  313.       else {
  314.         if (3 > strlen(dot + 1)) {  /* most likely in this program */
  315.           outfile = concat (infiles[i], "s", "");
  316.         }
  317.         else {
  318.           /* the whole extension is already taken */
  319.           outfile = concat (infiles[i], "", "");
  320.           idx = dot + 3 - infiles[i];
  321.           if ('s' == outfile[idx])
  322.         outfile[idx] = '_';
  323.           else
  324.         outfile[idx] = 's';
  325.         }
  326.       }
  327. #endif  /* atarist */
  328.     }
  329.  
  330.       if (ptr < MAX_IN_CORE_SORT)
  331.     /* Sort a small amount of data. */
  332.     sort_in_core (infiles[i], ptr, outfile);
  333.       else
  334.     sort_offline (infiles[i], ptr, outfile);
  335.     }
  336.  
  337.   flush_tempfiles (tempcount);
  338.   return (TI_NO_ERROR);
  339. }
  340.  
  341. void
  342. usage ()
  343. {
  344.   fprintf (stderr, "\
  345. Usage: %s [-k] infile [-o outfile] ...\n", program_name);
  346.   exit (1);
  347. }
  348.  
  349. /* Decode the command line arguments to set the parameter variables
  350.    and set up the vector of keyfields and the vector of input files. */
  351.  
  352. void
  353. decode_command (argc, argv)
  354.      int argc;
  355.      char **argv;
  356. {
  357.   int optc;
  358.   char **ip;
  359.   char **op;
  360.  
  361.   /* Store default values into parameter variables. */
  362.  
  363.   tempdir = getenv ("TMPDIR");
  364. #ifdef atarist
  365.   if (tempdir == NULL)
  366.       if (NULL == (tempdir = getenv ("TEMP")))
  367.       tempdir = ".";
  368. #endif /* atarist */
  369. #ifdef VMS
  370.   if (tempdir == NULL)
  371.     tempdir = "sys$scratch:";
  372. #else
  373.   if (tempdir == NULL)
  374.     tempdir = "/tmp/";
  375.   else
  376.     tempdir = concat (tempdir, "/", "");
  377. #endif
  378.  
  379.   keep_tempfiles = 0;
  380.  
  381.   /* Allocate ARGC input files, which must be enough.  */
  382.  
  383.   infiles = (char **) xmalloc (argc * sizeof (char *));
  384.   outfiles = (char **) xmalloc (argc * sizeof (char *));
  385.   ip = infiles;
  386.   op = outfiles;
  387.  
  388.   while ((optc = getopt (argc, argv, "-ko:")) != EOF)
  389.     {
  390.       switch (optc)
  391.     {
  392.     case 1:        /* Non-option filename. */
  393.       *ip++ = optarg;
  394.       *op++ = NULL;
  395.       break;
  396.  
  397.     case 'k':
  398.       keep_tempfiles = 1;
  399.       break;
  400.  
  401.     case 'o':
  402.       if (op > outfiles)
  403.         *(op - 1) = optarg;
  404.       break;
  405.  
  406.     default:
  407.       usage ();
  408.     }
  409.     }
  410.  
  411.   /* Record number of keyfields and terminate list of filenames. */
  412.   num_infiles = ip - infiles;
  413.   *ip = 0;
  414.   if (num_infiles == 0)
  415.     usage ();
  416. }
  417.  
  418. /* Return a name for a temporary file. */
  419.  
  420. char *
  421. maketempname (count)
  422.      int count;
  423. {
  424.   char tempsuffix[10];
  425. #ifndef atarist
  426.   sprintf (tempsuffix, "%d", count);
  427. #else  /* atarist */
  428.   sprintf (tempsuffix, ".%d", count);
  429. #endif /* atarist */
  430.   return concat (tempdir, tempbase, tempsuffix);
  431. }
  432.  
  433. /* Delete all temporary files up to TO_COUNT. */
  434.  
  435. void
  436. flush_tempfiles (to_count)
  437.      int to_count;
  438. {
  439.   if (keep_tempfiles)
  440.     return;
  441.   while (last_deleted_tempcount < to_count)
  442.     unlink (maketempname (++last_deleted_tempcount));
  443. }
  444.  
  445. /* Copy the input file open on IDESC into a temporary file
  446.    and return the temporary file name. */
  447.  
  448. #define BUFSIZE 1024
  449.  
  450. char *
  451. tempcopy (idesc)
  452.      int idesc;
  453. {
  454.   char *outfile = maketempname (++tempcount);
  455.   int odesc;
  456.   char buffer[BUFSIZE];
  457.  
  458.   odesc = open (outfile, O_WRONLY | O_CREAT, 0666);
  459.  
  460.   if (odesc < 0)
  461.     pfatal_with_name (outfile);
  462.  
  463.   while (1)
  464.     {
  465.       int nread = read (idesc, buffer, BUFSIZE);
  466.       write (odesc, buffer, nread);
  467.       if (!nread)
  468.     break;
  469.     }
  470.  
  471.   close (odesc);
  472.  
  473.   return outfile;
  474. }
  475.  
  476. /* Compare LINE1 and LINE2 according to the specified set of keyfields. */
  477.  
  478. int
  479. compare_full (line1, line2)
  480.      char **line1, **line2;
  481. {
  482.   int i;
  483.  
  484.   /* Compare using the first keyfield;
  485.      if that does not distinguish the lines, try the second keyfield;
  486.      and so on. */
  487.  
  488.   for (i = 0; i < num_keyfields; i++)
  489.     {
  490.       long length1, length2;
  491.       char *start1 = find_field (&keyfields[i], *line1, &length1);
  492.       char *start2 = find_field (&keyfields[i], *line2, &length2);
  493.       int tem = compare_field (&keyfields[i], start1, length1, *line1 - text_base,
  494.                    start2, length2, *line2 - text_base);
  495.       if (tem)
  496.     {
  497.       if (keyfields[i].reverse)
  498.         return -tem;
  499.       return tem;
  500.     }
  501.     }
  502.  
  503.   return 0;            /* Lines match exactly. */
  504. }
  505.  
  506. /* Compare LINE1 and LINE2, described by structures
  507.    in which the first keyfield is identified in advance.
  508.    For positional sorting, assumes that the order of the lines in core
  509.    reflects their nominal order.  */
  510.  
  511. int
  512. compare_prepared (line1, line2)
  513.      struct lineinfo *line1, *line2;
  514. {
  515.   int i;
  516.   int tem;
  517.   char *text1, *text2;
  518.  
  519.   /* Compare using the first keyfield, which has been found for us already. */
  520.   if (keyfields->positional)
  521.     {
  522.       if (line1->text - text_base > line2->text - text_base)
  523.     tem = 1;
  524.       else
  525.     tem = -1;
  526.     }
  527.   else if (keyfields->numeric)
  528.     tem = line1->key.number - line2->key.number;
  529.   else
  530.     tem = compare_field (keyfields, line1->key.text, line1->keylen, 0,
  531.              line2->key.text, line2->keylen, 0);
  532.   if (tem)
  533.     {
  534.       if (keyfields->reverse)
  535.     return -tem;
  536.       return tem;
  537.     }
  538.  
  539.   text1 = line1->text;
  540.   text2 = line2->text;
  541.  
  542.   /* Compare using the second keyfield;
  543.      if that does not distinguish the lines, try the third keyfield;
  544.      and so on. */
  545.  
  546.   for (i = 1; i < num_keyfields; i++)
  547.     {
  548.       long length1, length2;
  549.       char *start1 = find_field (&keyfields[i], text1, &length1);
  550.       char *start2 = find_field (&keyfields[i], text2, &length2);
  551.       int tem = compare_field (&keyfields[i], start1, length1, text1 - text_base,
  552.                    start2, length2, text2 - text_base);
  553.       if (tem)
  554.     {
  555.       if (keyfields[i].reverse)
  556.         return -tem;
  557.       return tem;
  558.     }
  559.     }
  560.  
  561.   return 0;            /* Lines match exactly. */
  562. }
  563.  
  564. /* Like compare_full but more general.
  565.    You can pass any strings, and you can say how many keyfields to use.
  566.    POS1 and POS2 should indicate the nominal positional ordering of
  567.    the two lines in the input.  */
  568.  
  569. int
  570. compare_general (str1, str2, pos1, pos2, use_keyfields)
  571.      char *str1, *str2;
  572.      long pos1, pos2;
  573.      int use_keyfields;
  574. {
  575.   int i;
  576.  
  577.   /* Compare using the first keyfield;
  578.      if that does not distinguish the lines, try the second keyfield;
  579.      and so on. */
  580.  
  581.   for (i = 0; i < use_keyfields; i++)
  582.     {
  583.       long length1, length2;
  584.       char *start1 = find_field (&keyfields[i], str1, &length1);
  585.       char *start2 = find_field (&keyfields[i], str2, &length2);
  586.       int tem = compare_field (&keyfields[i], start1, length1, pos1,
  587.                    start2, length2, pos2);
  588.       if (tem)
  589.     {
  590.       if (keyfields[i].reverse)
  591.         return -tem;
  592.       return tem;
  593.     }
  594.     }
  595.  
  596.   return 0;            /* Lines match exactly. */
  597. }
  598.  
  599. /* Find the start and length of a field in STR according to KEYFIELD.
  600.    A pointer to the starting character is returned, and the length
  601.    is stored into the int that LENGTHPTR points to.  */
  602.  
  603. char *
  604. find_field (keyfield, str, lengthptr)
  605.      struct keyfield *keyfield;
  606.      char *str;
  607.      long *lengthptr;
  608. {
  609.   char *start;
  610.   char *end;
  611.   char *(*fun) __PROTO((char*, int, int, int));
  612.  
  613.   if (keyfield->braced)
  614.     fun = find_braced_pos;
  615.   else
  616.     fun = find_pos;
  617.  
  618.   start = (*fun) (str, keyfield->startwords, keyfield->startchars,
  619.           keyfield->ignore_blanks);
  620.   if (keyfield->endwords < 0)
  621.     {
  622.       if (keyfield->braced)
  623.     end = find_braced_end (start);
  624.       else
  625.     {
  626.       end = start;
  627.       while (*end && *end != '\n')
  628.         end++;
  629.     }
  630.     }
  631.   else
  632.     {
  633.       end = (*fun) (str, keyfield->endwords, keyfield->endchars, 0);
  634.       if (end - str < start - str)
  635.     end = start;
  636.     }
  637.   *lengthptr = end - start;
  638.   return start;
  639. }
  640.  
  641. /* Return a pointer to a specified place within STR,
  642.    skipping (from the beginning) WORDS words and then CHARS chars.
  643.    If IGNORE_BLANKS is nonzero, we skip all blanks
  644.    after finding the specified word.  */
  645.  
  646. char *
  647. find_pos (str, words, chars, ignore_blanks)
  648.      char *str;
  649.      int words, chars;
  650.      int ignore_blanks;
  651. {
  652.   int i;
  653.   char *p = str;
  654.  
  655.   for (i = 0; i < words; i++)
  656.     {
  657.       char c;
  658.       /* Find next bunch of nonblanks and skip them. */
  659.       while ((c = *p) == ' ' || c == '\t')
  660.     p++;
  661.       while ((c = *p) && c != '\n' && !(c == ' ' || c == '\t'))
  662.     p++;
  663.       if (!*p || *p == '\n')
  664.     return p;
  665.     }
  666.  
  667.   while (*p == ' ' || *p == '\t')
  668.     p++;
  669.  
  670.   for (i = 0; i < chars; i++)
  671.     {
  672.       if (!*p || *p == '\n')
  673.     break;
  674.       p++;
  675.     }
  676.   return p;
  677. }
  678.  
  679. /* Like find_pos but assumes that each field is surrounded by braces
  680.    and that braces within fields are balanced. */
  681.  
  682. char *
  683. find_braced_pos (str, words, chars, ignore_blanks)
  684.      char *str;
  685.      int words, chars;
  686.      int ignore_blanks;
  687. {
  688.   int i;
  689.   int bracelevel;
  690.   char *p = str;
  691.   char c;
  692.  
  693.   for (i = 0; i < words; i++)
  694.     {
  695.       bracelevel = 1;
  696.       while ((c = *p++) != '{' && c != '\n' && c)
  697.     /* Do nothing. */ ;
  698.       if (c != '{')
  699.     return p - 1;
  700.       while (bracelevel)
  701.     {
  702.       c = *p++;
  703.       if (c == '{')
  704.         bracelevel++;
  705.       if (c == '}')
  706.         bracelevel--;
  707.       if (c == 0 || c == '\n')
  708.         return p - 1;
  709.     }
  710.     }
  711.  
  712.   while ((c = *p++) != '{' && c != '\n' && c)
  713.     /* Do nothing. */ ;
  714.  
  715.   if (c != '{')
  716.     return p - 1;
  717.  
  718.   if (ignore_blanks)
  719.     while ((c = *p) == ' ' || c == '\t')
  720.       p++;
  721.  
  722.   for (i = 0; i < chars; i++)
  723.     {
  724.       if (!*p || *p == '\n')
  725.     break;
  726.       p++;
  727.     }
  728.   return p;
  729. }
  730.  
  731. /* Find the end of the balanced-brace field which starts at STR.
  732.    The position returned is just before the closing brace. */
  733.  
  734. char *
  735. find_braced_end (str)
  736.      char *str;
  737. {
  738.   int bracelevel;
  739.   char *p = str;
  740.   char c;
  741.  
  742.   bracelevel = 1;
  743.   while (bracelevel)
  744.     {
  745.       c = *p++;
  746.       if (c == '{')
  747.     bracelevel++;
  748.       if (c == '}')
  749.     bracelevel--;
  750.       if (c == 0 || c == '\n')
  751.     return p - 1;
  752.     }
  753.   return p - 1;
  754. }
  755.  
  756. long
  757. find_value (start, length)
  758.      char *start;
  759.      long length;
  760. {
  761.   while (length != 0L)
  762.     {
  763.       if (isdigit (*start))
  764.     return atol (start);
  765.       length--;
  766.       start++;
  767.     }
  768.   return 0l;
  769. }
  770.  
  771. /* Vector used to translate characters for comparison.
  772.    This is how we make all alphanumerics follow all else,
  773.    and ignore case in the first sorting.  */
  774. int char_order[256];
  775.  
  776. void
  777. init_char_order ()
  778. {
  779.   int i;
  780.   for (i = 1; i < 256; i++)
  781.     char_order[i] = i;
  782.  
  783.   for (i = '0'; i <= '9'; i++)
  784.     char_order[i] += 512;
  785.  
  786.   for (i = 'a'; i <= 'z'; i++)
  787.     {
  788.       char_order[i] = 512 + i;
  789.       char_order[i + 'A' - 'a'] = 512 + i;
  790.     }
  791. }
  792.  
  793. /* Compare two fields (each specified as a start pointer and a character count)
  794.    according to KEYFIELD.
  795.    The sign of the value reports the relation between the fields. */
  796.  
  797. int
  798. compare_field (keyfield, start1, length1, pos1, start2, length2, pos2)
  799.      struct keyfield *keyfield;
  800.      char *start1;
  801.      long length1;
  802.      long pos1;
  803.      char *start2;
  804.      long length2;
  805.      long pos2;
  806. {
  807.   if (keyfields->positional)
  808.     {
  809.       if (pos1 > pos2)
  810.     return 1;
  811.       else
  812.     return -1;
  813.     }
  814.   if (keyfield->numeric)
  815.     {
  816.       long value = find_value (start1, length1) - find_value (start2, length2);
  817.       if (value > 0)
  818.     return 1;
  819.       if (value < 0)
  820.     return -1;
  821.       return 0;
  822.     }
  823.   else
  824.     {
  825.       char *p1 = start1;
  826.       char *p2 = start2;
  827.       char *e1 = start1 + length1;
  828.       char *e2 = start2 + length2;
  829.  
  830.       while (1)
  831.     {
  832.       int c1, c2;
  833.  
  834.       if (p1 == e1)
  835.         c1 = 0;
  836.       else
  837.         c1 = *p1++;
  838.       if (p2 == e2)
  839.         c2 = 0;
  840.       else
  841.         c2 = *p2++;
  842.  
  843.       if (char_order[c1] != char_order[c2])
  844.         return char_order[c1] - char_order[c2];
  845.       if (!c1)
  846.         break;
  847.     }
  848.  
  849.       /* Strings are equal except possibly for case.  */
  850.       p1 = start1;
  851.       p2 = start2;
  852.       while (1)
  853.     {
  854.       int c1, c2;
  855.  
  856.       if (p1 == e1)
  857.         c1 = 0;
  858.       else
  859.         c1 = *p1++;
  860.       if (p2 == e2)
  861.         c2 = 0;
  862.       else
  863.         c2 = *p2++;
  864.  
  865.       if (c1 != c2)
  866.         /* Reverse sign here so upper case comes out last.  */
  867.         return c2 - c1;
  868.       if (!c1)
  869.         break;
  870.     }
  871.  
  872.       return 0;
  873.     }
  874. }
  875.  
  876. /* A `struct linebuffer' is a structure which holds a line of text.
  877.    `readline' reads a line from a stream into a linebuffer
  878.    and works regardless of the length of the line.  */
  879.  
  880. /**
  881. struct linebuffer
  882. {
  883.   long size;
  884.   char *buffer;
  885. };
  886. **/
  887.  
  888. /* Initialize LINEBUFFER for use. */
  889.  
  890. void
  891. initbuffer (linebuffer)
  892.      struct linebuffer *linebuffer;
  893. {
  894.   linebuffer->size = 200;
  895.   linebuffer->buffer = (char *) xmalloc (200);
  896. }
  897.  
  898. /* Read a line of text from STREAM into LINEBUFFER.
  899.    Return the length of the line.  */
  900.  
  901. long
  902. readline (linebuffer, stream)
  903.      struct linebuffer *linebuffer;
  904.      FILE *stream;
  905. {
  906.   char *buffer = linebuffer->buffer;
  907.   char *p = linebuffer->buffer;
  908.   char *end = p + linebuffer->size;
  909.  
  910.   while (1)
  911.     {
  912.       int c = getc (stream);
  913.       if (p == end)
  914.     {
  915.       buffer = (char *) xrealloc (buffer, linebuffer->size *= 2);
  916.       p += buffer - linebuffer->buffer;
  917.       end += buffer - linebuffer->buffer;
  918.       linebuffer->buffer = buffer;
  919.     }
  920.       if (c < 0 || c == '\n')
  921.     {
  922.       *p = 0;
  923.       break;
  924.     }
  925.       *p++ = c;
  926.     }
  927.  
  928.   return p - buffer;
  929. }
  930.  
  931. /* Sort an input file too big to sort in core.  */
  932.  
  933. void
  934. sort_offline (infile, /* nfiles,*/ total, outfile)
  935.      char *infile;
  936.      /* int nfiles;  *//* UNUSED */
  937.      long total;
  938.      char *outfile;
  939. {
  940.   /* More than enough. */
  941.   int ntemps = 2 * (total + MAX_IN_CORE_SORT - 1) / MAX_IN_CORE_SORT;
  942.   char **tempfiles = (char **) xmalloc (ntemps * sizeof (char *));
  943.   FILE *istream = fopen (infile, "r");
  944.   int i;
  945.   struct linebuffer lb;
  946.   long linelength;
  947.   int failure = 0;
  948.  
  949.   initbuffer (&lb);
  950.  
  951.   /* Read in one line of input data.  */
  952.  
  953.   linelength = readline (&lb, istream);
  954.  
  955.   if (lb.buffer[0] != '\\' && lb.buffer[0] != '@')
  956.     {
  957.       error ("%s: not a texinfo index file", infile);
  958.       return;
  959.     }
  960.  
  961.   /* Split up the input into `ntemps' temporary files, or maybe fewer,
  962.      and put the new files' names into `tempfiles' */
  963.  
  964.   for (i = 0; i < ntemps; i++)
  965.     {
  966.       char *outname = maketempname (++tempcount);
  967.       FILE *ostream = fopen (outname, "w");
  968.       long tempsize = 0;
  969.  
  970.       if (!ostream)
  971.     pfatal_with_name (outname);
  972.       tempfiles[i] = outname;
  973.  
  974.       /* Copy lines into this temp file as long as it does not make file
  975.      "too big" or until there are no more lines.  */
  976.  
  977.       while (tempsize + linelength + 1 <= MAX_IN_CORE_SORT)
  978.     {
  979.       tempsize += linelength + 1;
  980.       fputs (lb.buffer, ostream);
  981.       putc ('\n', ostream);
  982.  
  983.       /* Read another line of input data.  */
  984.  
  985.       linelength = readline (&lb, istream);
  986.       if (!linelength && feof (istream))
  987.         break;
  988.  
  989.       if (lb.buffer[0] != '\\' && lb.buffer[0] != '@')
  990.         {
  991.           error ("%s: not a texinfo index file", infile);
  992.           failure = 1;
  993.           goto fail;
  994.         }
  995.     }
  996.       fclose (ostream);
  997.       if (feof (istream))
  998.     break;
  999.     }
  1000.  
  1001.   free (lb.buffer);
  1002.  
  1003. fail:
  1004.   /* Record number of temp files we actually needed.  */
  1005.  
  1006.   ntemps = i;
  1007.  
  1008.   /* Sort each tempfile into another tempfile.
  1009.     Delete the first set of tempfiles and put the names of the second
  1010.     into `tempfiles'. */
  1011.  
  1012.   for (i = 0; i < ntemps; i++)
  1013.     {
  1014.       char *newtemp = maketempname (++tempcount);
  1015.       sort_in_core ((char *)&tempfiles[i], MAX_IN_CORE_SORT, newtemp);
  1016.       if (!keep_tempfiles)
  1017.     unlink (tempfiles[i]);
  1018.       tempfiles[i] = newtemp;
  1019.     }
  1020.  
  1021.   if (failure)
  1022.     return;
  1023.  
  1024.   /* Merge the tempfiles together and indexify. */
  1025.  
  1026.   merge_files (tempfiles, ntemps, outfile);
  1027. }
  1028.  
  1029. /* Sort INFILE, whose size is TOTAL,
  1030.    assuming that is small enough to be done in-core,
  1031.    then indexify it and send the output to OUTFILE (or to stdout).  */
  1032.  
  1033. void
  1034. sort_in_core (infile, total, outfile)
  1035.      char *infile;
  1036.      long total;
  1037.      char *outfile;
  1038. {
  1039.   char **nextline;
  1040.   char *data = (char *) xmalloc (total + 1);
  1041.   char *file_data;
  1042.   long file_size;
  1043.   int i;
  1044.   FILE *ostream = stdout;
  1045.   struct lineinfo *lineinfo;
  1046.  
  1047.   /* Read the contents of the file into the moby array `data'. */
  1048.  
  1049.   int desc = open (infile, O_RDONLY, 0);
  1050.  
  1051.   if (desc < 0)
  1052.     fatal ("failure reopening %s", infile);
  1053.   for (file_size = 0;;)
  1054.     {
  1055.       i = read (desc, data + file_size, total - file_size);
  1056.       if (i <= 0)
  1057.     break;
  1058.       file_size += i;
  1059.     }
  1060.   file_data = data;
  1061.   data[file_size] = 0;
  1062.  
  1063.   close (desc);
  1064.  
  1065.   if (file_size > 0 && data[0] != '\\' && data[0] != '@')
  1066.     {
  1067.       error ("%s: not a texinfo index file", infile);
  1068.       return;
  1069.     }
  1070.  
  1071.   init_char_order ();
  1072.  
  1073.   /* Sort routines want to know this address. */
  1074.  
  1075.   text_base = data;
  1076.  
  1077.   /* Create the array of pointers to lines, with a default size
  1078.      frequently enough.  */
  1079.  
  1080.   nlines = total / 50;
  1081.   if (!nlines)
  1082.     nlines = 2;
  1083.   linearray = (char **) xmalloc (nlines * sizeof (char *));
  1084.  
  1085.   /* `nextline' points to the next free slot in this array.
  1086.      `nlines' is the allocated size.  */
  1087.  
  1088.   nextline = linearray;
  1089.  
  1090.   /* Parse the input file's data, and make entries for the lines.  */
  1091.  
  1092.   nextline = parsefile (infile, nextline, file_data, file_size);
  1093.   if (nextline == 0)
  1094.     {
  1095.       error ("%s: not a texinfo index file", infile);
  1096.       return;
  1097.     }
  1098.  
  1099.   /* Sort the lines. */
  1100.  
  1101.   /* If we have enough space, find the first keyfield of each line in advance.
  1102.      Make a `struct lineinfo' for each line, which records the keyfield
  1103.      as well as the line, and sort them.  */
  1104.  
  1105.   lineinfo = (struct lineinfo *) malloc ((nextline - linearray) * sizeof (struct lineinfo));
  1106.  
  1107.   if (lineinfo)
  1108.     {
  1109.       struct lineinfo *lp;
  1110.       char **p;
  1111.  
  1112.       for (lp = lineinfo, p = linearray; p != nextline; lp++, p++)
  1113.     {
  1114.       lp->text = *p;
  1115.       lp->key.text = find_field (keyfields, *p, &lp->keylen);
  1116.       if (keyfields->numeric)
  1117.         lp->key.number = find_value (lp->key.text, lp->keylen);
  1118.     }
  1119.  
  1120.       qsort (lineinfo, nextline - linearray, sizeof (struct lineinfo), compare_prepared);
  1121.  
  1122.       for (lp = lineinfo, p = linearray; p != nextline; lp++, p++)
  1123.     *p = lp->text;
  1124.  
  1125.       free (lineinfo);
  1126.     }
  1127.   else
  1128.     qsort (linearray, nextline - linearray, sizeof (char *), compare_full);
  1129.  
  1130.   /* Open the output file. */
  1131.  
  1132.   if (outfile)
  1133.     {
  1134.       ostream = fopen (outfile, "w");
  1135.       if (!ostream)
  1136.     pfatal_with_name (outfile);
  1137.     }
  1138.  
  1139.   writelines (linearray, nextline - linearray, ostream);
  1140.   if (outfile)
  1141.     fclose (ostream);
  1142.  
  1143.   free (linearray);
  1144.   free (data);
  1145. }
  1146.  
  1147. /* Parse an input string in core into lines.
  1148.    DATA is the input string, and SIZE is its length.
  1149.    Data goes in LINEARRAY starting at NEXTLINE.
  1150.    The value returned is the first entry in LINEARRAY still unused.
  1151.    Value 0 means input file contents are invalid.  */
  1152.  
  1153. char **
  1154. parsefile (filename, nextline, data, size)
  1155.      char *filename;
  1156.      char **nextline;
  1157.      char *data;
  1158.      long size;
  1159. {
  1160.   char *p, *end;
  1161.   char **line = nextline;
  1162.  
  1163.   p = data;
  1164.   end = p + size;
  1165.   *end = 0;
  1166.  
  1167.   while (p != end)
  1168.     {
  1169.       if (p[0] != '\\' && p[0] != '@')
  1170.     return 0;
  1171.  
  1172.       *line = p;
  1173.       while (*p && *p != '\n')
  1174.     p++;
  1175.       if (p != end)
  1176.     p++;
  1177.  
  1178.       line++;
  1179.       if (line == linearray + nlines)
  1180.     {
  1181.       char **old = linearray;
  1182.       linearray = (char **) xrealloc (linearray, sizeof (char *) * (nlines *= 4));
  1183.       line += linearray - old;
  1184.     }
  1185.     }
  1186.  
  1187.   return line;
  1188. }
  1189.  
  1190. /* Indexification is a filter applied to the sorted lines
  1191.    as they are being written to the output file.
  1192.    Multiple entries for the same name, with different page numbers,
  1193.    get combined into a single entry with multiple page numbers.
  1194.    The first braced field, which is used for sorting, is discarded.
  1195.    However, its first character is examined, folded to lower case,
  1196.    and if it is different from that in the previous line fed to us
  1197.    a \initial line is written with one argument, the new initial.
  1198.  
  1199.    If an entry has four braced fields, then the second and third
  1200.    constitute primary and secondary names.
  1201.    In this case, each change of primary name
  1202.    generates a \primary line which contains only the primary name,
  1203.    and in between these are \secondary lines which contain
  1204.    just a secondary name and page numbers. */
  1205.  
  1206. /* The last primary name we wrote a \primary entry for.
  1207.    If only one level of indexing is being done, this is the last name seen. */
  1208. char *lastprimary;
  1209. /* Length of storage allocated for lastprimary. */
  1210. int lastprimarylength;
  1211.  
  1212. /* Similar, for the secondary name. */
  1213. char *lastsecondary;
  1214. int lastsecondarylength;
  1215.  
  1216. /* Zero if we are not in the middle of writing an entry.
  1217.    One if we have written the beginning of an entry but have not
  1218.    yet written any page numbers into it.
  1219.    Greater than one if we have written the beginning of an entry
  1220.    plus at least one page number. */
  1221. int pending;
  1222.  
  1223. /* The initial (for sorting purposes) of the last primary entry written.
  1224.    When this changes, a \initial {c} line is written */
  1225.  
  1226. char *lastinitial;
  1227.  
  1228. int lastinitiallength;
  1229.  
  1230. /* When we need a string of length 1 for the value of lastinitial,
  1231.    store it here.  */
  1232.  
  1233. char lastinitial1[2];
  1234.  
  1235. /* Initialize static storage for writing an index. */
  1236.  
  1237. void
  1238. init_index ()
  1239. {
  1240.   pending = 0;
  1241.   lastinitial = lastinitial1;
  1242.   lastinitial1[0] = 0;
  1243.   lastinitial1[1] = 0;
  1244.   lastinitiallength = 0;
  1245.   lastprimarylength = 100;
  1246.   lastprimary = (char *) xmalloc (lastprimarylength + 1);
  1247.   bzero (lastprimary, lastprimarylength + 1);
  1248.   lastsecondarylength = 100;
  1249.   lastsecondary = (char *) xmalloc (lastsecondarylength + 1);
  1250.   bzero (lastsecondary, lastsecondarylength + 1);
  1251. }
  1252.  
  1253. /* Indexify.  Merge entries for the same name,
  1254.    insert headers for each initial character, etc.  */
  1255.  
  1256. void
  1257. indexify (line, ostream)
  1258.      char *line;
  1259.      FILE *ostream;
  1260. {
  1261.   char *primary, *secondary, *pagenumber;
  1262.   long primarylength, secondarylength = 0, pagelength;
  1263.   int nosecondary;
  1264.   long initiallength;
  1265.   char *initial;
  1266.   char initial1[2];
  1267.   register char *p;
  1268.  
  1269.   /* First, analyze the parts of the entry fed to us this time. */
  1270.  
  1271.   p = find_braced_pos (line, 0, 0, 0);
  1272.   if (*p == '{')
  1273.     {
  1274.       initial = p;
  1275.       /* Get length of inner pair of braces starting at `p',
  1276.      including that inner pair of braces.  */
  1277.       initiallength = find_braced_end (p + 1) + 1 - p;
  1278.     }
  1279.   else
  1280.     {
  1281.       initial = initial1;
  1282.       initial1[0] = *p;
  1283.       initial1[1] = 0;
  1284.       initiallength = 1;
  1285.  
  1286.       if (initial1[0] >= 'a' && initial1[0] <= 'z')
  1287.     initial1[0] -= 040;
  1288.     }
  1289.  
  1290.   pagenumber = find_braced_pos (line, 1, 0, 0);
  1291.   pagelength = find_braced_end (pagenumber) - pagenumber;
  1292.   if (pagelength == 0)
  1293.     abort ();
  1294.  
  1295.   primary = find_braced_pos (line, 2, 0, 0);
  1296.   primarylength = find_braced_end (primary) - primary;
  1297.  
  1298.   secondary = find_braced_pos (line, 3, 0, 0);
  1299.   nosecondary = !*secondary;
  1300.   if (!nosecondary)
  1301.     secondarylength = find_braced_end (secondary) - secondary;
  1302.  
  1303.   /* If the primary is different from before, make a new primary entry. */
  1304.   if (strncmp (primary, lastprimary, primarylength))
  1305.     {
  1306.       /* Close off current secondary entry first, if one is open. */
  1307.       if (pending)
  1308.     {
  1309.       fputs ("}\n", ostream);
  1310.       pending = 0;
  1311.     }
  1312.  
  1313.       /* If this primary has a different initial, include an entry for
  1314.      the initial. */
  1315.       if (initiallength != lastinitiallength ||
  1316.       strncmp (initial, lastinitial, initiallength))
  1317.     {
  1318.       fprintf (ostream, "\\initial {");
  1319.       fwrite (initial, 1, initiallength, ostream);
  1320.       fputs ("}\n", ostream);
  1321. /*      fprintf (ostream, "}\n", initial); */
  1322.       if (initial == initial1)
  1323.         {
  1324.           lastinitial = lastinitial1;
  1325.           *lastinitial1 = *initial1;
  1326.         }
  1327.       else
  1328.         {
  1329.           lastinitial = initial;
  1330.         }
  1331.       lastinitiallength = initiallength;
  1332.     }
  1333.  
  1334.       /* Make the entry for the primary.  */
  1335.       if (nosecondary)
  1336.     fputs ("\\entry {", ostream);
  1337.       else
  1338.     fputs ("\\primary {", ostream);
  1339.       fwrite (primary, primarylength, 1, ostream);
  1340.       if (nosecondary)
  1341.     {
  1342.       fputs ("}{", ostream);
  1343.       pending = 1;
  1344.     }
  1345.       else
  1346.     fputs ("}\n", ostream);
  1347.  
  1348.       /* Record name of most recent primary. */
  1349.       if (lastprimarylength < primarylength)
  1350.     {
  1351.       lastprimarylength = primarylength + 100;
  1352.       lastprimary = (char *) xrealloc (lastprimary,
  1353.                        1 + lastprimarylength);
  1354.     }
  1355.       strncpy (lastprimary, primary, primarylength);
  1356.       lastprimary[primarylength] = 0;
  1357.  
  1358.       /* There is no current secondary within this primary, now. */
  1359.       lastsecondary[0] = 0;
  1360.     }
  1361.  
  1362.   /* Should not have an entry with no subtopic following one with a subtopic. */
  1363.  
  1364.   if (nosecondary && *lastsecondary)
  1365.     error ("entry %s follows an entry with a secondary name", line);
  1366.  
  1367.   /* Start a new secondary entry if necessary. */
  1368.   if (!nosecondary && strncmp (secondary, lastsecondary, secondarylength))
  1369.     {
  1370.       if (pending)
  1371.     {
  1372.       fputs ("}\n", ostream);
  1373.       pending = 0;
  1374.     }
  1375.  
  1376.       /* Write the entry for the secondary.  */
  1377.       fputs ("\\secondary {", ostream);
  1378.       fwrite (secondary, secondarylength, 1, ostream);
  1379.       fputs ("}{", ostream);
  1380.       pending = 1;
  1381.  
  1382.       /* Record name of most recent secondary. */
  1383.       if (lastsecondarylength < secondarylength)
  1384.     {
  1385.       lastsecondarylength = secondarylength + 100;
  1386.       lastsecondary = (char *) xrealloc (lastsecondary,
  1387.                          1 + lastsecondarylength);
  1388.     }
  1389.       strncpy (lastsecondary, secondary, secondarylength);
  1390.       lastsecondary[secondarylength] = 0;
  1391.     }
  1392.  
  1393.   /* Here to add one more page number to the current entry. */
  1394.   if (pending++ != 1)
  1395.     fputs (", ", ostream);    /* Punctuate first, if this is not the first. */
  1396.   fwrite (pagenumber, pagelength, 1, ostream);
  1397. }
  1398.  
  1399. /* Close out any unfinished output entry. */
  1400.  
  1401. void
  1402. finish_index (ostream)
  1403.      FILE *ostream;
  1404. {
  1405.   if (pending)
  1406.     fputs ("}\n", ostream);
  1407.   free (lastprimary);
  1408.   free (lastsecondary);
  1409. }
  1410.  
  1411. /* Copy the lines in the sorted order.
  1412.    Each line is copied out of the input file it was found in. */
  1413.  
  1414. void
  1415. writelines (linearray, nlines, ostream)
  1416.      char **linearray;
  1417.      int nlines;
  1418.      FILE *ostream;
  1419. {
  1420.   char **stop_line = linearray + nlines;
  1421.   char **next_line;
  1422.  
  1423.   init_index ();
  1424.  
  1425.   /* Output the text of the lines, and free the buffer space. */
  1426.  
  1427.   for (next_line = linearray; next_line != stop_line; next_line++)
  1428.     {
  1429.       /* If -u was specified, output the line only if distinct from previous one.  */
  1430.       if (next_line == linearray
  1431.       /* Compare previous line with this one, using only the
  1432.          explicitly specd keyfields. */
  1433.       || compare_general (*(next_line - 1), *next_line, 0L, 0L, num_keyfields - 1))
  1434.     {
  1435.       char *p = *next_line;
  1436.       char c;
  1437.  
  1438.       while ((c = *p++) && c != '\n')
  1439.         /* Do nothing. */ ;
  1440.       *(p - 1) = 0;
  1441.       indexify (*next_line, ostream);
  1442.     }
  1443.     }
  1444.  
  1445.   finish_index (ostream);
  1446. }
  1447.  
  1448. /* Assume (and optionally verify) that each input file is sorted;
  1449.    merge them and output the result.
  1450.    Returns nonzero if any input file fails to be sorted.
  1451.  
  1452.    This is the high-level interface that can handle an unlimited
  1453.    number of files.  */
  1454.  
  1455. #define MAX_DIRECT_MERGE 10
  1456.  
  1457. int
  1458. merge_files (infiles, nfiles, outfile)
  1459.      char **infiles;
  1460.      int nfiles;
  1461.      char *outfile;
  1462. {
  1463.   char **tempfiles;
  1464.   int ntemps;
  1465.   int i;
  1466.   int value = 0;
  1467.   int start_tempcount = tempcount;
  1468.  
  1469.   if (nfiles <= MAX_DIRECT_MERGE)
  1470.     return merge_direct (infiles, nfiles, outfile);
  1471.  
  1472.   /* Merge groups of MAX_DIRECT_MERGE input files at a time,
  1473.      making a temporary file to hold each group's result.  */
  1474.  
  1475.   ntemps = (nfiles + MAX_DIRECT_MERGE - 1) / MAX_DIRECT_MERGE;
  1476.   tempfiles = (char **) xmalloc (ntemps * sizeof (char *));
  1477.   for (i = 0; i < ntemps; i++)
  1478.     {
  1479.       int nf = MAX_DIRECT_MERGE;
  1480.       if (i + 1 == ntemps)
  1481.     nf = nfiles - i * MAX_DIRECT_MERGE;
  1482.       tempfiles[i] = maketempname (++tempcount);
  1483.       value |= merge_direct (&infiles[i * MAX_DIRECT_MERGE], nf, tempfiles[i]);
  1484.     }
  1485.  
  1486.   /* All temporary files that existed before are no longer needed
  1487.      since their contents have been merged into our new tempfiles.
  1488.      So delete them.  */
  1489.   flush_tempfiles (start_tempcount);
  1490.  
  1491.   /* Now merge the temporary files we created.  */
  1492.  
  1493.   merge_files (tempfiles, ntemps, outfile);
  1494.  
  1495.   free (tempfiles);
  1496.  
  1497.   return value;
  1498. }
  1499.  
  1500. /* Assume (and optionally verify) that each input file is sorted;
  1501.    merge them and output the result.
  1502.    Returns nonzero if any input file fails to be sorted.
  1503.  
  1504.    This version of merging will not work if the number of
  1505.    input files gets too high.  Higher level functions
  1506.    use it only with a bounded number of input files.  */
  1507.  
  1508. int
  1509. merge_direct (infiles, nfiles, outfile)
  1510.      char **infiles;
  1511.      int nfiles;
  1512.      char *outfile;
  1513. {
  1514.   struct linebuffer *lb1, *lb2;
  1515.   struct linebuffer **thisline, **prevline;
  1516.   FILE **streams;
  1517.   int i;
  1518.   int nleft;
  1519.   int lossage = 0;
  1520.   int *file_lossage;
  1521.   struct linebuffer *prev_out = 0;
  1522.   FILE *ostream = stdout;
  1523.  
  1524.   if (outfile)
  1525.     {
  1526.       ostream = fopen (outfile, "w");
  1527.     }
  1528.   if (!ostream)
  1529.     pfatal_with_name (outfile);
  1530.  
  1531.   init_index ();
  1532.  
  1533.   if (nfiles == 0)
  1534.     {
  1535.       if (outfile)
  1536.     fclose (ostream);
  1537.       return 0;
  1538.     }
  1539.  
  1540.   /* For each file, make two line buffers.
  1541.      Also, for each file, there is an element of `thisline'
  1542.      which points at any time to one of the file's two buffers,
  1543.      and an element of `prevline' which points to the other buffer.
  1544.      `thisline' is supposed to point to the next available line from the file,
  1545.      while `prevline' holds the last file line used,
  1546.      which is remembered so that we can verify that the file is properly sorted. */
  1547.  
  1548.   /* lb1 and lb2 contain one buffer each per file. */
  1549.   lb1 = (struct linebuffer *) xmalloc (nfiles * sizeof (struct linebuffer));
  1550.   lb2 = (struct linebuffer *) xmalloc (nfiles * sizeof (struct linebuffer));
  1551.  
  1552.   /* thisline[i] points to the linebuffer holding the next available line in file i,
  1553.      or is zero if there are no lines left in that file.  */
  1554.   thisline = (struct linebuffer **)
  1555.     xmalloc (nfiles * sizeof (struct linebuffer *));
  1556.   /* prevline[i] points to the linebuffer holding the last used line
  1557.      from file i.  This is just for verifying that file i is properly
  1558.      sorted.  */
  1559.   prevline = (struct linebuffer **)
  1560.     xmalloc (nfiles * sizeof (struct linebuffer *));
  1561.   /* streams[i] holds the input stream for file i.  */
  1562.   streams = (FILE **) xmalloc (nfiles * sizeof (FILE *));
  1563.   /* file_lossage[i] is nonzero if we already know file i is not
  1564.      properly sorted.  */
  1565.   file_lossage = (int *) xmalloc (nfiles * sizeof (int));
  1566.  
  1567.   /* Allocate and initialize all that storage. */
  1568.  
  1569.   for (i = 0; i < nfiles; i++)
  1570.     {
  1571.       initbuffer (&lb1[i]);
  1572.       initbuffer (&lb2[i]);
  1573.       thisline[i] = &lb1[i];
  1574.       prevline[i] = &lb2[i];
  1575.       file_lossage[i] = 0;
  1576.       streams[i] = fopen (infiles[i], "r");
  1577.       if (!streams[i])
  1578.     pfatal_with_name (infiles[i]);
  1579.  
  1580.       readline (thisline[i], streams[i]);
  1581.     }
  1582.  
  1583.   /* Keep count of number of files not at eof. */
  1584.   nleft = nfiles;
  1585.  
  1586.   while (nleft)
  1587.     {
  1588.       struct linebuffer *best = 0;
  1589.       struct linebuffer *exch;
  1590.       int bestfile = -1;
  1591.       int i;
  1592.  
  1593.       /* Look at the next avail line of each file; choose the least one.  */
  1594.  
  1595.       for (i = 0; i < nfiles; i++)
  1596.     {
  1597.       if (thisline[i] &&
  1598.           (!best ||
  1599.            0 < compare_general (best->buffer, thisline[i]->buffer,
  1600.                  (long) bestfile, (long) i, num_keyfields)))
  1601.         {
  1602.           best = thisline[i];
  1603.           bestfile = i;
  1604.         }
  1605.     }
  1606.  
  1607.       /* Output that line, unless it matches the previous one and we
  1608.      don't want duplicates. */
  1609.  
  1610.       if (!(prev_out &&
  1611.         !compare_general (prev_out->buffer,
  1612.                   best->buffer, 0L, 1L, num_keyfields - 1)))
  1613.     indexify (best->buffer, ostream);
  1614.       prev_out = best;
  1615.  
  1616.       /* Now make the line the previous of its file, and fetch a new
  1617.      line from that file.  */
  1618.  
  1619.       exch = prevline[bestfile];
  1620.       prevline[bestfile] = thisline[bestfile];
  1621.       thisline[bestfile] = exch;
  1622.  
  1623.       while (1)
  1624.     {
  1625.       /* If the file has no more, mark it empty. */
  1626.  
  1627.       if (feof (streams[bestfile]))
  1628.         {
  1629.           thisline[bestfile] = 0;
  1630.           /* Update the number of files still not empty. */
  1631.           nleft--;
  1632.           break;
  1633.         }
  1634.       readline (thisline[bestfile], streams[bestfile]);
  1635.       if (thisline[bestfile]->buffer[0] || !feof (streams[bestfile]))
  1636.         break;
  1637.     }
  1638.     }
  1639.  
  1640.   finish_index (ostream);
  1641.  
  1642.   /* Free all storage and close all input streams. */
  1643.  
  1644.   for (i = 0; i < nfiles; i++)
  1645.     {
  1646.       fclose (streams[i]);
  1647.       free (lb1[i].buffer);
  1648.       free (lb2[i].buffer);
  1649.     }
  1650.   free (file_lossage);
  1651.   free (lb1);
  1652.   free (lb2);
  1653.   free (thisline);
  1654.   free (prevline);
  1655.   free (streams);
  1656.  
  1657.   if (outfile)
  1658.     fclose (ostream);
  1659.  
  1660.   return lossage;
  1661. }
  1662.  
  1663. /* Print error message and exit.  */
  1664.  
  1665. void
  1666. fatal (s1, s2)
  1667.      char *s1, *s2;
  1668. {
  1669.   error (s1, s2);
  1670.   exit (TI_FATAL_ERROR);
  1671. }
  1672.  
  1673. /* Print error message.  S1 is printf control string, S2 is arg for it. */
  1674.  
  1675. void
  1676. error (s1, s2)
  1677.      char *s1, *s2;
  1678. {
  1679.   printf ("%s: ", program_name);
  1680.   printf (s1, s2);
  1681.   printf ("\n");
  1682. }
  1683.  
  1684. void
  1685. perror_with_name (name)
  1686.      char *name;
  1687. {
  1688.   char *s;
  1689.  
  1690.   if (errno < sys_nerr)
  1691.     s = concat ("", sys_errlist[errno], " for %s");
  1692.   else
  1693.     s = "cannot open %s";
  1694.   error (s, name);
  1695. }
  1696.  
  1697. void
  1698. pfatal_with_name (name)
  1699.      char *name;
  1700. {
  1701.   char *s;
  1702.  
  1703.   if (errno < sys_nerr)
  1704.     s = concat ("", sys_errlist[errno], " for %s");
  1705.   else
  1706.     s = "cannot open %s";
  1707.   fatal (s, name);
  1708. }
  1709.  
  1710. /* Return a newly-allocated string whose contents concatenate those of
  1711.    S1, S2, S3.  */
  1712.  
  1713. char *
  1714. concat (s1, s2, s3)
  1715.      char *s1, *s2, *s3;
  1716. {
  1717.   size_t len1 = strlen (s1), len2 = strlen (s2), len3 = strlen (s3);
  1718.   char *result = (char *) xmalloc (len1 + len2 + len3 + 1);
  1719.  
  1720.   strcpy (result, s1);
  1721.   strcpy (result + len1, s2);
  1722.   strcpy (result + len1 + len2, s3);
  1723.   *(result + len1 + len2 + len3) = 0;
  1724.  
  1725.   return result;
  1726. }
  1727.  
  1728. /* Just like malloc, but kills the program in case of fatal error. */
  1729. void *
  1730. xmalloc (nbytes)
  1731.      size_t nbytes;
  1732. {
  1733.   void *temp = (void *) malloc (nbytes);
  1734.  
  1735.   if (nbytes && temp == (void *)NULL)
  1736.     memory_error ("xmalloc", nbytes);
  1737.  
  1738.   return (temp);
  1739. }
  1740.  
  1741. /* Like realloc (), but barfs if there isn't enough memory. */
  1742. void *
  1743. xrealloc (pointer, nbytes)
  1744.      void *pointer;
  1745.      size_t nbytes;
  1746. {
  1747.   void *temp;
  1748.  
  1749.   if (!pointer)
  1750.     temp = (void *)xmalloc (nbytes);
  1751.   else
  1752.     temp = (void *)realloc (pointer, nbytes);
  1753.  
  1754.   if (nbytes && !temp)
  1755.     memory_error ("xrealloc", nbytes);
  1756.  
  1757.   return (temp);
  1758. }
  1759.  
  1760. int
  1761. memory_error (callers_name, bytes_wanted)
  1762.      char *callers_name;
  1763.      size_t bytes_wanted;
  1764. {
  1765.   char printable_string[80];
  1766.  
  1767.   sprintf (printable_string,
  1768.        "Virtual memory exhausted in %s ()!  Needed %lu bytes.",
  1769.        callers_name, bytes_wanted);
  1770.  
  1771.   error (printable_string, 0);
  1772.   abort ();
  1773. }
  1774.  
  1775. #ifndef STDC_HEADERS
  1776. void
  1777. bzero (b, length)
  1778.      register char *b;
  1779.      register long length;
  1780. {
  1781. #ifdef VMS
  1782.   short zero = 0;
  1783.   long max_str = 65535;
  1784.  
  1785.   while (length > max_str)
  1786.     {
  1787.       (void) LIB$MOVC5 (&zero, &zero, &zero, &max_str, b);
  1788.       length -= max_str;
  1789.       b += max_str;
  1790.     }
  1791.   (void) LIB$MOVC5 (&zero, &zero, &zero, &length, b);
  1792. #else
  1793.   while (length-- > 0)
  1794.     *b++ = 0;
  1795. #endif /* not VMS */
  1796. }
  1797. #endif /* not STDC_HEADERS */
  1798.